package com.gxa.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 朱雄
 * Date: 2020/09/22 17:27
 * Description:
 * Version: V1.0
 * @author
 */
public class UploadFileUtil {
    /**
     *创建一个map集合用于存放表单数据
     *
     */
    public static Map<String,Object> formData=new HashMap<>();

    public static String [] uploadFile(HttpServletRequest request, MultipartFile[] file) throws FileUploadException, IOException {
        String[] src=new String[file.length];
        for (int i=0;i<file.length;i++) {
            if (!file[i].isEmpty()) {
                Date date=new Date();
                int year=date.getYear()+1900;
                int month=date.getMonth()+1;
                int day=date.getDate();
                String uploadPath = request.getServletContext().getRealPath("/") +File.separator+"upload"+File.separator+year+File.separator+month+File.separator+day+File.separator;
                String fileName = file[i].getOriginalFilename();
                String ext=fileName.substring(fileName.lastIndexOf("."),fileName.length());
                File newFile = new File(uploadPath);
                //没有目录就创建
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                String newFileName= UuidUtil.getUUID()+ext;
                File upNewFile = new File(uploadPath + newFileName);
                String str= File.separator+"upload"+File.separator+year+File.separator+month+File.separator+day+File.separator+newFileName;
                src[i]=str.replace("\\","/");
                System.out.println("upNewFile=" + str.replace("\\","/"));
                FileCopyUtils.copy(file[i].getBytes(), upNewFile);
            }
        }
            return src;
    }
}
